import React, { useState } from 'react';
import { Button, Card, Space, message, Divider } from 'antd';
import { SafetyOutlined, LockOutlined, DeleteOutlined, SendOutlined, PictureOutlined } from '@ant-design/icons';
import { useVerify } from '../../contexts/VerifyContext';
import { showVcodeVerify } from '../../utils/verifyHelper';
import './VerifyDemo.scss';

const VerifyDemo: React.FC = () => {
  const { showVerify } = useVerify();
  const [loading, setLoading] = useState(false);
  const [clickCount, setClickCount] = useState(0);

  // 示例1：使用 Hook
  const handleUseHook = async () => {
    setLoading(true);
    const isVerified = await showVerify({
      title: '使用 Hook 示例',
      description: '这是通过 useVerify Hook 触发的图形验证码',
    });

    setLoading(false);
    if (isVerified) {
      message.success('验证成功！');
    } else {
      message.error('验证失败或已取消');
    }
  };

  // 示例2：图形验证辅助函数
  const handleVcodeHelper = async () => {
    setLoading(true);
    const isVerified = await showVcodeVerify(
      '图形验证示例',
      '请输入图片中的验证码'
    );

    setLoading(false);
    if (isVerified) {
      message.success('验证通过！');
    }
  };

  // 示例3：带回调的验证
  const handleWithCallbacks = async () => {
    setLoading(true);
    const isVerified = await showVerify({
      title: '带回调示例',
      description: '这个验证配置了成功和失败回调',
      onSuccess: (data) => {
        console.log('验证成功，数据：', data);
        message.success(`验证成功！票据: ${data?.ticket || 'N/A'}`);
      },
      onFail: (error) => {
        console.log('验证失败，错误：', error);
        message.error(`验证失败: ${error?.msg || '请重试'}`);
      },
      onClose: () => {
        console.log('用户关闭了验证窗口');
      },
    });

    setLoading(false);
    console.log('最终验证结果：', isVerified);
  };

  // 示例4：模拟删除操作
  const handleDelete = async () => {
    const confirmed = window.confirm('确定要删除吗？');
    if (!confirmed) return;

    setLoading(true);
    const isVerified = await showVcodeVerify(
      '确认删除',
      '删除是敏感操作，请完成图形验证'
    );

    if (isVerified) {
      setTimeout(() => {
        setLoading(false);
        message.success('删除成功！');
      }, 500);
    } else {
      setLoading(false);
      message.warning('验证失败，删除已取消');
    }
  };

  // 示例5：模拟高频操作
  const handleFrequentAction = async () => {
    setClickCount(prev => prev + 1);

    // 连续点击3次触发验证
    if (clickCount >= 2) {
      setLoading(true);
      const isVerified = await showVerify({
        title: '操作频率验证',
        description: '检测到频繁操作，请完成图形验证后继续',
      });

      if (isVerified) {
        setClickCount(0);
        setLoading(false);
        message.success('验证通过，计数器已重置');
      } else {
        setLoading(false);
        message.warning('验证失败，请稍后再试');
      }
    } else {
      message.info(`操作成功 (${clickCount + 1}/3)`);
    }
  };

  // 示例6：模拟表单提交
  const handleSubmitForm = async () => {
    setLoading(true);
    const isVerified = await showVcodeVerify(
      '表单提交验证',
      '请完成图形验证以提交表单'
    );

    if (isVerified) {
      setTimeout(() => {
        setLoading(false);
        message.success('表单提交成功！');
      }, 500);
    } else {
      setLoading(false);
      message.error('验证失败，表单未提交');
    }
  };

  return (
    <div className="verify-demo">
      <div className="demo-header">
        <h1>
          <PictureOutlined /> 全局图形验证码系统演示
        </h1>
        <p>基于 react-vcode 的全局验证系统</p>
      </div>

      <div className="demo-content">
        {/* 基础使用 */}
        <Card title="基础使用" className="demo-card">
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            <div className="demo-item">
              <h4>1. 使用 Hook 触发验证</h4>
              <p>在组件中使用 <code>useVerify()</code> Hook</p>
              <Button
                type="primary"
                icon={<SafetyOutlined />}
                onClick={handleUseHook}
                loading={loading}
              >
                触发验证（Hook 方式）
              </Button>
            </div>

            <Divider />

            <div className="demo-item">
              <h4>2. 使用辅助函数 - 图形验证码</h4>
              <p>使用 <code>showVcodeVerify()</code> 快速触发图形验证</p>
              <Button
                type="primary"
                icon={<PictureOutlined />}
                onClick={handleVcodeHelper}
                loading={loading}
              >
                图形验证
              </Button>
            </div>

            <Divider />

            <div className="demo-item">
              <h4>3. 带回调的验证</h4>
              <p>配置 <code>onSuccess</code>, <code>onFail</code>, <code>onClose</code> 回调</p>
              <Button
                type="primary"
                onClick={handleWithCallbacks}
                loading={loading}
              >
                触发验证（带回调）
              </Button>
            </div>
          </Space>
        </Card>

        {/* 实际场景 */}
        <Card title="实际应用场景" className="demo-card">
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            <div className="demo-item">
              <h4>场景1：删除操作验证</h4>
              <p>在执行删除等敏感操作前，要求用户完成验证</p>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleDelete}
                loading={loading}
              >
                删除项目
              </Button>
            </div>

            <Divider />

            <div className="demo-item">
              <h4>场景2：高频操作限制</h4>
              <p>连续点击3次后触发验证（当前: {clickCount}/3）</p>
              <Button
                type="default"
                onClick={handleFrequentAction}
                loading={loading}
              >
                频繁操作按钮 ({clickCount}/3)
              </Button>
            </div>

            <Divider />

            <div className="demo-item">
              <h4>场景3：表单提交验证</h4>
              <p>提交表单前要求完成图形验证</p>
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSubmitForm}
                loading={loading}
              >
                提交表单
              </Button>
            </div>
          </Space>
        </Card>

        {/* 代码示例 */}
        <Card title="代码示例" className="demo-card">
          <div className="code-example">
            <h4>使用 Hook：</h4>
            <pre>{`import { useVerify } from '@/contexts/VerifyContext';

const { showVerify } = useVerify();

const isVerified = await showVerify({
  title: '安全验证',
  description: '请输入图片中的验证码',
});

if (isVerified) {
  // 验证成功
}`}</pre>

            <h4>使用辅助函数：</h4>
            <pre>{`import { showVcodeVerify } from '@/utils/verifyHelper';

// 图形验证
const isVerified = await showVcodeVerify('标题', '描述');`}</pre>
          </div>
        </Card>

        {/* 说明 */}
        <Card title="📝 使用说明" className="demo-card info-card">
          <ul>
            <li><LockOutlined /> <strong>图形验证码</strong>：输入图片中显示的字符完成验证</li>
            <li><LockOutlined /> <strong>简单易用</strong>：经典的图形验证码形式，用户体验好</li>
            <li><LockOutlined /> <strong>可刷新</strong>：点击刷新按钮重新生成验证码</li>
            <li><LockOutlined /> <strong>自动重试</strong>：API拦截器在连续错误3次后自动触发验证</li>
            <li><LockOutlined /> <strong>429状态码</strong>：请求频率过高时自动触发验证</li>
            <li><LockOutlined /> <strong>Promise异步</strong>：所有验证都返回Promise，便于async/await使用</li>
          </ul>
        </Card>

        {/* 文档链接 */}
        <Card className="demo-card docs-card">
          <h3>📚 完整文档</h3>
          <p>查看 <code>docs/VERIFY_SYSTEM.md</code> 了解更多详细信息和高级用法</p>
          <p>图形验证码库：<a href="https://www.npmjs.com/package/react-vcode" target="_blank" rel="noopener noreferrer">react-vcode</a></p>
        </Card>
      </div>
    </div>
  );
};

export default VerifyDemo;
